import Vue from 'vue'
import VueRouter from 'vue-router'
import Main from '../components/Main'
import Login from '../views/login/Login'
import Register from '../views/login/Register'
import userProfile from '../views/user/UserProfile'
import HomePage from '../components/HomePage'
import StudentInfo from '../views/user/StudentInfo'
import StudentHomePage from '../components/StudentHomePage'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

// 安装路由
Vue.use(VueRouter)
// 配置导出路由
const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/Main',
      name: 'Main',
      component: Main,
      redirect: () => computeRoute(), // 默认子路由
      children: [
        {path: '/user/profile', meta: {name: '我的信息'}, component: userProfile},
        {path: '/HomePage', meta: {name: '班级整体课堂专注度'}, component: HomePage},
        {path: '/StudentInfo', meta: {name: '班级学生列表'}, component: StudentInfo},
        {path: '/Student/HomePage', meta: {name: '个人近期课堂专注度'}, component: StudentHomePage}
      ]
    },
    {
      path: '/login',
      name: 'login',
      meta: {name: '登录'},
      component: Login
    },
    {
      path: '/register',
      name: 'register',
      meta: {name: '注册'},
      component: Register
    },
    { path: '/', redirect: '/login' }
  ],
  data: function () {
    return {
      redirectPath: null
    }
  }
})

// 全局前置守卫，在每次路由导航时都会执行
router.beforeEach((to, from, next) => {
  console.log('Navigating from:', from, to, next)
  // 如果不是登录页，存储当前页面的路由信息
  if (to.name !== 'login' && to.name !== 'register') {
    sessionStorage.setItem('lastPath', JSON.stringify(to.path))
  }
  next()
})

// 计算路由的方法
function computeRoute () {
  const lastPath = JSON.parse(sessionStorage.getItem('lastPath'))
  if (lastPath) {
    return lastPath
  } else {
    return '/login'
  }
}

// 导出 router 实例
export default router
